package light.head.controller.oa;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.VehicleApplyDAO;
import light.head.dao.oa.VehicleAssignDAO;
import light.head.dao.oa.VehicleDAO;
import light.head.dao.oa.VehicleTypeDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.MD5Utils;
import light.head.model.UserInfo;
import light.head.model.Vehicle;
import light.head.model.VehicleApply;
import light.head.model.VehicleApplyItem;
import light.head.model.VehicleAssign;
import light.head.model.VehicleType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(Url.C_VEHICLE)
public class VehicleController extends SupporterController{
	
	private VehicleDAO vehicleDAO;
	private VehicleTypeDAO vtDAO;
	private VehicleApplyDAO vaDAO;
	private VehicleAssignDAO asDAO;
	private OrganDAO organDAO;
	private UserInfoDAO uDAO;
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.VEHICLE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println(cu_organCode(request));
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.PLATE, Parm.STATUS);
		map.put(Parm.OC, cu_organCode(request).toString());
		if (vehicleDAO.findByMap(map, pb) == RESULT.SUCCESS){
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.VEHICLE_LIST);
	}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Vehicle vehicle = vehicleDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.VEHICLE, vehicle);
		}
		List<VehicleType> typeList = vtDAO.findByOc(cu_organCode(request));
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			
			for (VehicleType type : typeList){
				result.append("{");
				result.append("\"vtn\":\"" + type.getName() +"\",");
				result.append("\"vtc\":\"" + type.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		} 
		return new ModelAndView(Url.VEHICLE_EDIT);
	}
	
	// 指派页面
	@RequestMapping(value = Url.ASSIGN)
	public ModelAndView assign(Integer code,HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(code != null){
			VehicleApply apply = vaDAO.get(code);
			List<VehicleApplyItem> list = vaDAO.findApplyItem(code);
			
			
			for (VehicleApplyItem item : list) {
				item.setVehicleList(vehicleDAO.findByVtc(cu_organCode(request), item.getVtc())); // 可用车辆的信息
			}
			apply.setAdList(list);
			request.setAttribute(Parm.APPLY, apply);	// 申请信息
			
		}
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		List<UserInfo> typeList = uDAO.findOc(organDAO.getSonCodeList(oc));
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			for (UserInfo user : typeList){
				result.append("{");
				result.append("\"dn\":\"" + user.getRealName() +"\",");
				result.append("\"dc\":\"" + user.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		} 
		return new ModelAndView(Url.VEHICLE_ASSIGN);
	}
	
	//归还页面
	@RequestMapping(value = Url.RETURNVEHICLE)
	public ModelAndView returnVehicle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Vehicle vehicle = vehicleDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.VEHICLE, vehicle);
		}
		
		return new ModelAndView(Url.VEHICLE_RETURN_INIT);
	}
	//保存归还信息
	@RequestMapping(value = Url.RETURNINFO)
	public void returnInfo(String ekm,String plate,HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (ekm == null || plate == null) return;
		
		VehicleAssign as = asDAO.findPlate(plate);
		as.setRevert(true);
		as.setEkm(ekm);
		as.setRt(new Date());
		result = asDAO.upd(as);
		
		Vehicle ve = vehicleDAO.findByPlate(plate);
		ve.setStatus(Sys.B_TWO);
		ve.setUn(null);
		result = vehicleDAO.upd(ve);
		if (result == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		if (vehicleDAO.del(Integer.parseInt(code)) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else 
			print(response, Msg.ERROR);
	}
	//添加车辆信息
	@RequestMapping(Url.SAVE)
	public void save(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		List<Vehicle> v = vehicleDAO.findPlate(vehicle.getPlate());
		if (v != null && v.size() != 0) {
			print(response, Msg.EXISTS);
			return;
		}
		if (vehicle.getCode() != null) {
			Vehicle old = vehicleDAO.get(vehicle.getCode());
			List<VehicleType> iac = vtDAO.findByNameOc(vehicle.getVtn(), cu_organCode(request));
			if (iac == null || iac.size() == 0)  {
				VehicleType vt = new VehicleType();
				vt.setCu(cu_code(request));
				vt.setCt(new Date());
				vt.setDeleted(false);
				vt.setName(vehicle.getVtn());
				vt.setOc(old.getOc());
				vtDAO.add(vt);
				old.setVtc(vt.getCode());
			}
			old.setName(vehicle.getName());
			old.setPrice(vehicle.getPrice());
			old.setPlate(vehicle.getPlate());
			old.setVtn(vehicle.getVtn());
			result = vehicleDAO.upd(old);
		} else {
			if(null == vehicle.getVtn()) {
				print(response, Msg.NULL_TYPE);
				return;
			}
			if(null == vehicle.getPrice()) {
				print(response, Msg.NULL_PRICE);
				return;
			}
			if(vehicle.getName().equals("")) {
				print(response, Msg.NULL_NAME);
				return;
			}
			if(vehicle.getPlate().equals("")) {
				print(response, Msg.NULL_PLATE);
				return;
			}
			List<VehicleType> iac = vtDAO.findByNameOc(vehicle.getVtn(), cu_organCode(request));
			if (iac == null || iac.size() == 0)  {
				VehicleType vt = new VehicleType();
				vt.setCu(cu_code(request));
				vt.setCt(new Date());
				vt.setDeleted(false);
				vt.setName(vehicle.getVtn());
				vt.setOc(cu_organCode(request));
				vtDAO.add(vt);
				vehicle.setVtc(vt.getCode());
			}
			vehicle.setCu(cu_code(request));
			vehicle.setCt(new Date());
			vehicle.setDeleted(false);
			vehicle.setOc(cu_organCode(request));
			vehicle.setStatus(Sys.B_TWO);
			result = vehicleDAO.add(vehicle);
		}
		
		if (RESULT.SUCCESS == result) {
			vehicleDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	/** 密码验证弹出框 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(String plate,HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (plate == null) return null;
		VehicleAssign va = asDAO.findPlate(plate);
		request.setAttribute(Parm.LIST, va);
		return new ModelAndView(Url.VEHICLE_AFFIRM);
	}
	
	
	/** 下面几个方法是选择申请单时使用 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.VEHICLE_APPLY_INIT);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.TITLE, Parm.DELETED, Parm.OC,Parm.CN);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == vaDAO.findByMapOcs(organDAO.getSonCodeList(oc), map, pb)){
			VehicleApply apply = null;
			for (Object o : pb.getResultList()) {
				apply = (VehicleApply) o;
				apply.setAdList(vaDAO.findApplyItem(apply.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.VEHICLE_APPLY_LIST);
	}
	
	//保存指派信息
	@RequestMapping(Url.SAVEASSIGN)
	public void saveAssign(VehicleAssign vas, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		String cn =request.getParameter(Parm.CN);
		if (vas.getList() != null && vas.getList().size() >0) {
			int i = 0;
			for(VehicleAssign va : vas.getList()) {
				if (va.getPlate() != null) {
					va.setCt(new Date());
					va.setCu(cu_code(request));
					va.setOc(cu_organCode(request));
					va.setDeleted(false);
					va.setRevert(false);
					va.setUn(cn);
					result = asDAO.add(va);
					
					Vehicle v = vehicleDAO.get(va.getVc());
					v.setUn(cn);
					v.setStatus(Sys.B_ONE);
					vehicleDAO.upd(v);
					i ++;
				} 
			}
			if (i == 0) {
				print(response, Msg.EXISTS);
				return;
			}
			VehicleApply apply = vaDAO.get(vas.getList().get(0).getVac());
			apply.setDesignate(true);
			apply.setStatus(Sys.B_TWO);
			vaDAO.upd(apply);
		}
		if (RESULT.SUCCESS == result) {
			vehicleDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	
	
	//验证密码
	@RequestMapping(value = Url.AFFIRM)
	public void affirm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String cu= request.getParameter(Parm.CU);
		String pwd = request.getParameter(Parm.PWD);

		if (cu == "" || pwd == "") {
			print(response,Msg.PARAMETER_ERROR);
			return;
		}
		UserInfo user = uDAO.getAffirm(Integer.parseInt(cu), pwd);
		if (user == null) {
			print(response, Msg.ERROR);
			return;
		}
		if (!user.getPwd().equals(MD5Utils.encryptTo32(pwd))) {
			print(response, Msg.EXISTS);
		} else {
			print(response, Msg.SUCCESS);
		}
	}

	@Autowired
	public void setVehicleDAO(VehicleDAO vehicleDAO) {
		this.vehicleDAO = vehicleDAO;
	}
	@Autowired
	public void setVtDAO(VehicleTypeDAO vtDAO) {
		this.vtDAO = vtDAO;
	}
	@Autowired
	public void setVaDAO(VehicleApplyDAO vaDAO) {
		this.vaDAO = vaDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setuDAO(UserInfoDAO uDAO) {
		this.uDAO = uDAO;
	}
	@Autowired
	public void setAsDAO(VehicleAssignDAO asDAO) {
		this.asDAO = asDAO;
	}


}
